import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_shop/res/colors.dart';
import 'package:flutter_shop/res/dimens.dart';
import 'package:flutter_shop/res/styles.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

///loading加载框
class Loading {
  factory Loading(BuildContext context) => _getInstance(context);

  static Loading _instance;

  static Loading _getInstance(BuildContext context) {
    if (_instance == null) {
      _instance = Loading._internal(context);
    }
    return _instance;
  }

  Loading._internal(BuildContext context) {
    this.context = context;
    _overlayState = Overlay.of(context);
  }

  BuildContext context;
  OverlayState _overlayState;
  OverlayEntry _overlayEntry;
  bool _isShowLoading = false;

  ///展示loading框
  static void showLoading({String msg = "加载中...", bool canDimiss = false, LoadingWidgetStateController controller}) {
    if (!_instance._isShowLoading) {
      _instance._overlayEntry = new OverlayEntry(builder: (context) {
        return LoadingWidget(msg, canDimiss, controller: controller);
      });
      _instance._overlayState.insert(_instance._overlayEntry);
      _instance._isShowLoading = true;
    }
  }

  ///取消loading框
  static void cancelLoading() {
    if (_instance._isShowLoading) {
      try {
        _instance._overlayEntry?.remove();
        _instance._overlayEntry = null;
        _instance._isShowLoading = false;
      } catch (e) {
        print(e);
      }
    }
  }
}

///loading控件
class LoadingWidget extends StatefulWidget {
  String msg;
  bool canDimiss;
  LoadingWidgetStateController controller;

  LoadingWidget(this.msg, this.canDimiss, {this.controller});

  @override
  _LoadingWidgetState createState() => _LoadingWidgetState();
}

class _LoadingWidgetState extends State<LoadingWidget> {
  double _opacity = 0.0;
  String _msg = "";
  bool _canDimiss = false;

  @override
  void initState() {
    super.initState();
    _msg = widget.msg;
    _canDimiss = widget.canDimiss;
  }

  @override
  void buildComplete() {
    setState(() {
      _opacity = 1.0;
    });
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    widget.controller?.bindLoadingWidgetState(this);
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: AnimatedOpacity(
        opacity: _opacity,
        duration: Duration(milliseconds: 0),
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: <Widget>[
            AbsorbPointer(
              absorbing: !_canDimiss,
              child: GestureDetector(
                onTap: () {
                  if (_canDimiss) {
                    Loading.cancelLoading();
                  }
                },
                child: Container(
                  width: double.infinity,
                  height: double.infinity,
                  color: Colors.black.withOpacity(0.5),
                ),
              ),
            ),
            Container(
              width: 130,
              height: 120,
              padding: EdgeInsets.symmetric(horizontal: 10),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SpinKitCircle(
                    color: CommonColors.primary,
                    size: 60,
                  ),
                  Gaps.v_gap_10,
                  Text(_msg,
                      style: TextStyle(
                        fontSize: CommonDimens.font_size_small,
                        color: CommonColors.black,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis)
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///更新消息
  void updateMsg(String msg) {
    setState(() {
      _msg = msg;
    });
  }
}

///加载控件状态控制器
class LoadingWidgetStateController {
  _LoadingWidgetState _state;

  void bindLoadingWidgetState(_LoadingWidgetState state) {
    this._state = state;
  }

  ///更新msg
  void updateMsg(String msg) {
    _state?.updateMsg(msg);
  }
}
